import logging  # 新增：导入logging模块
from urllib.parse import urlencode

import requests

from utils.baidu_map_api import BaiduMapAPI

logger = logging.getLogger('baidu_map_service')  # 新增：获取已配置的日志记录器

class BaiduMapService:
    def __init__(self, cache):
        self.cache = cache
        # 硬编码有效AK（请替换为真实AK）
        self.ak = '47jXQbiwPNWVY5GgVPUJYpOiHG5YhBcr'
        self.baidu_map_api = BaiduMapAPI(self.ak)
        logger.info('百度地图服务初始化完成，AK长度：%s', len(self.ak))

    def search_places(self, query, region):
        logger.info(f"开始搜索地点: query={query}, region={region}")
        params = {
            "query": query,
            "region": region,
            "output": "json",
            "ak": '47jXQbiwPNWVY5GgVPUJYpOiHG5YhBcr',  # 直接硬编码有效AK
        }
        logger.debug('搜索地点请求参数: %s', {k:v for k,v in params.items() if k != 'ak'})
        try:
            full_url = f"http://api.map.baidu.com/place/v2/search?{urlencode(params)}"
            logger.info(f"请求的完整URL: {full_url}")  # 新增：记录完整请求URL
            response = requests.get(full_url)
            response.raise_for_status()
            data = response.json()

            if data.get("status") == 240:
                logger.error("百度地图API服务被禁用，请检查您的API密钥是否有效。")
                return []
            elif data.get("status") != 0:
                logger.error(f"百度地图API返回错误: {data.get('message')}")
                return []

            results = data.get('results', [])
            parsed_places = []
            for result in results:
                name = result.get("name")
                location = result.get("location")
                duration = result.get("detail_info", {}).get("duration", 0)
                if name and location:
                    parsed_places.append({
                        "name": name,
                        "location": f"{location['lng']},{location['lat']}",
                        "duration": duration
                    })

            logger.info(f"地点搜索完成: {len(parsed_places)}个地点")
            return parsed_places
        except requests.exceptions.RequestException as e:
            logger.error(f"百度地图API请求失败: {str(e)}")
            return []
        except ValueError as e:
            logger.error(f"解析百度地图API返回的数据失败: {str(e)}")
            return []
        except Exception as e:
            logger.error(f"未知错误: {str(e)}")
            return []

    # 修改驾车路线URL生成方法（修正API端点路径）
    def get_driving_direction_url(self, origin, destination, waypoints=None, tactics=0, origin_road_type=0):
        params = {
            "origin": f'{origin.split(",")[1]},{origin.split(",")[0]}',
            "destination": f'{destination.split(",")[1]},{destination.split(",")[0]}',
            "tactics": tactics,
            "origin_road_type": origin_road_type,
            "ak": '47jXQbiwPNWVY5GgVPUJYpOiHG5YhBcr'  # 修正后的有效AK
        }
        if waypoints:
            params["waypoints"] = "|".join(waypoints)
        return f"{base_url}?{urlencode(params)}"

    # 修改骑行路线URL生成方法
    def get_riding_direction_url(self, origin, destination, waypoints=None, riding_type=0, road_prefer=0):
        # 验证坐标格式
        if not self._validate_coordinate(origin) or not self._validate_coordinate(destination):
            logger.error("坐标格式错误，应为'纬度,经度'格式，当前参数 origin: %s destination: %s", origin, destination)
            raise ValueError("坐标格式错误")

        base_url = "https://api.map.baidu.com/directionlite/v1/riding"
        params = {
            "origin": origin,
            "destination": destination,
            "riding_type": riding_type,
            "road_prefer": road_prefer,
            "ak": self.ak,
        }
        if waypoints:
            params["waypoints"] = "|".join(waypoints)
        return f"{base_url}?{urlencode(params)}"

    # 新增坐标验证方法
    def _validate_coordinate(self, coord):
        try:
            lat, lng = map(float, coord.split(','))
            return -90 <= lat <= 90 and -180 <= lng <= 180
        except Exception as e:
            logger.error("坐标解析失败: %s 错误: %s", coord, str(e))
            return False

    # 修改步行路线URL生成方法
    def get_walking_direction_url(self, origin, destination):
        if not self._validate_coordinate(origin) or not self._validate_coordinate(destination):
            logger.error("步行路线坐标格式错误 origin: %s destination: %s", origin, destination)
            raise ValueError("坐标格式错误")

        base_url = "https://map.baidu.com/direction"
        params = {
            "origin": origin,
            "destination": destination,
            "mode": "walking",
            "output": "embed",
            "ak": self.ak,
        }
        logger.debug("步行路线请求参数: %s", params)
        return f"{base_url}?{urlencode(params)}"
